package com.maezia.tdr.common;

import cn.hutool.core.date.DateUtil;
import com.maezia.tdr.common.annotation.DateTimeFormat;
import com.maezia.tdr.common.enums.CheckDateEnum;
import com.maezia.tdr.common.enums.StatusCodeEnum;
import com.maezia.tdr.common.exception.DriveException;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;

@Slf4j
public class DateTimeValidator implements ConstraintValidator<DateTimeFormat, String> {

    private CheckDateEnum checkDate;

    @Override
    public void initialize(DateTimeFormat annotation) {
        this.checkDate = annotation.type();
    }

    @SneakyThrows
    @Override
    public boolean isValid(String date, ConstraintValidatorContext context) {
        if((checkDate == CheckDateEnum.START || checkDate == CheckDateEnum.END) && StringUtils.isEmpty(date)){
            throw new DriveException(checkDate == CheckDateEnum.START ? StatusCodeEnum.UTC_START_TIME_NOT_NULL : StatusCodeEnum.UTC_END_TIME_NOT_NULL);
        }

        String pattern = "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$";
        if ((checkDate == CheckDateEnum.START || checkDate == CheckDateEnum.END) && !Pattern.matches(pattern, date)) {
            throw new DriveException(checkDate == CheckDateEnum.START ? StatusCodeEnum.INVALID_UTC_START_TIME_FORMAT : StatusCodeEnum.INVALID_UTC_END_TIME_FORMAT);
        }

        try {
            DateUtil.parse(date, CommonConstant.UTC_DATE_TIME_FORMAT);
        }catch (Exception e){
            throw new DriveException(checkDate == CheckDateEnum.START ? StatusCodeEnum.INVALID_UTC_START_TIME_FORMAT : StatusCodeEnum.INVALID_UTC_END_TIME_FORMAT);
        }
        return true;
    }
}
